package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.Region;
import cn.wolfcode.luowowo.query.RegionQuery;
import cn.wolfcode.luowowo.repository.RegionRepository;
import cn.wolfcode.luowowo.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

@Service
public class RegionServiceImpl implements IRegionService {
    @Autowired
    private RegionRepository regionRepository;

    //mongodb数据库的查询对象
    @Autowired
    private MongoTemplate template;



    @Override
    public Region get(String id) {
        Optional<Region> Id = regionRepository.findById(id);
        return Id.orElse(null);
    }


    //实现分页的界面
    @Override
    public Page<Region> query(RegionQuery qo) {
        //条件
        Query query = new Query();
        //查询总条数
        long count = template.count(query, Region.class);
        //单前页面显示数据集合 list ,(-id倒叙方式)
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1,
                qo.getPageSize(), Sort.Direction.DESC, "_id");
        List<Region> list = template.find(query, Region.class);
        return new PageImpl<>(list,pageable,count);
    }

    //添加或修改操作
    @Override
    public void saveOrUpdate(Region region) {
        //判断是给添加还是修改
        if(StringUtils.hasLength(region.getId())){
            this.update(region);
        }else {
            this.save(region);
        }





    }

    @Override
    public void changeHotValue(String id, int hot) {

    }

    //删除方法
    @Override
    public void delete(String id) {
        regionRepository.deleteById(id);

    }

    @Override
    public List<Region> queryHotRegion() {
        return null;
    }

    @Override
    public void save(Region region) {
        region.setId(null);
        regionRepository.save(region);

    }

    @Override
    public void update(Region region) {
        regionRepository.save(region);
    }
}
